/*********************************************************************************
 *      Copyright:  (C) 2018 Wu Yujun<540726307@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  shared_mem_write.c
 *    Description:  This file is write to shared memory for IPC program 
 *                 
 *        Version:  1.0.0(2018年12月26日)
 *         Author:  Wu Yujun <540726307@qq.com>
 *      ChangeLog:  1, Release initial version on "2018年12月26日 20时02分16秒"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define     BUF_SIZE 128


typedef struct _st_student_info
{
    char    name[BUF_SIZE] ;
    long      ID ;
}student ;


int main(int argc, char **argv)
{
    key_t       key ;
    student     *stu = NULL;
    int         shmid ;

    key = ftok(".",0x98) ;
    if(key == -1)
    {
        printf("ftok() failed: %s\n", strerror(errno)) ;
        return -1 ;
    }
    printf("ftok() sucessful,key = %d\n", key) ;
    shmid =  shmget(key, sizeof(student), IPC_CREAT|0644);
    if( shmid == -1 )
    {
        printf("shmget() failed: %s\n", strerror(errno)) ;
        return -2 ;
    }
    printf("shmid = %d\n", shmid);
    stu = shmat(shmid, NULL, 0);
    if(stu == (void *) -1 )
    {
        printf("shmat failed: %s\n", strerror(errno)) ;
        shmctl(shmid, IPC_RMID, NULL) ;
        return -3 ;
    }
    snprintf(stu->name, sizeof(stu->name), "吴宇骏" ) ;
    stu->ID = 201621112125 ;
    printf("shmat sucessful, student name:%s ID: %ld\n", stu->name, stu->ID) ;
    shmdt(stu) ;            //关闭映射
    printf("Finish write to memory...\n") ;
    

    

    return 0 ;
}

